package com.liferay.portal.events;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hoperay.util.GeoLocation;
import com.hoperay.util.MaxMindUtil;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.struts.LastPath;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.ListType;
import com.liferay.portal.model.User;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.ListTypeServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.slayer.model.AddressExt;
import com.slayer.service.AddressExtLocalServiceUtil;

public class DefaultLandingPageAction2 extends Action {
	/* (non-Java-doc)
	 * @see com.liferay.portal.kernel.events.Action#Action()
	 */
	public DefaultLandingPageAction2() {
		super();
	}

	/* (non-Java-doc)
	 * @see com.liferay.portal.kernel.events.Action#run(HttpServletRequest arg0, HttpServletResponse arg1)
	 */
	public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {

		try {
			doRun(request, response);
		}
		catch (Exception e) {
			throw new ActionException(e);
		}
	}
		
	protected void doRun(
			HttpServletRequest request, HttpServletResponse response)
		throws Exception {

		long companyId = PortalUtil.getCompanyId(request);

		String path = PrefsPropsUtil.getString(
			companyId, PropsKeys.DEFAULT_LANDING_PAGE_PATH);
		
		// line inserted by mPower Labs
		path = getLandingPath(request, path);

		if (_log.isInfoEnabled()) {
			_log.info(
				PropsKeys.DEFAULT_LANDING_PAGE_PATH + StringPool.EQUAL + path);
		}

		if (Validator.isNotNull(path)) {
			LastPath lastPath = new LastPath(StringPool.BLANK, path);

			HttpSession session = request.getSession();

			session.setAttribute(WebKeys.LAST_PATH, lastPath);
		}
	}	
	
	/**
	 * method added by mPower Labs
	 */
	private String getLandingPath(HttpServletRequest request, String originalPath) throws PortalException,SystemException{
		
		String newPath = originalPath;
		
		User user = PortalUtil.getUser(request);
		
		boolean coordinatesSet = LandingPageHelperUtil.areCoordinatesSet(user);
		
		bindLocationToSession(request, user);
		if (!coordinatesSet) {
			newPath = "/web/guest/my-coordinates";
		} 
		
		return newPath;
	}
	
	private void bindLocationToSession(HttpServletRequest request, User user) {

		String ipAddress = PortalUtil.getOriginalServletRequest(request).getRemoteAddr();
		
		if (!userHasAddress(user)) {
			insertAddressEntry(MaxMindUtil.getLocation(ipAddress), user);
		} 
		
		HttpSession session = request.getSession();
		session.setAttribute("USER_GEO_LOCATION", new GeoLocation(user));
	}

	private boolean userHasAddress(User user) {
		// TODO Auto-generated method stub
		
		boolean flag = false;
		
		try {
			List<Address> userAddresses = user.getAddresses();
			for (Address userAddress: userAddresses) {
				if (userAddress.isPrimary()) {
					flag = true;
					break;
				}
			}
	
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}

	private void insertAddressEntry(GeoLocation geoLocation, User user) {
		// TODO Auto-generated method stub
		
		Address address = null;
		AddressExt addressExt = null;

		long addressId = 0l;
		try {
			addressId = CounterLocalServiceUtil.increment();
			addressExt = AddressExtLocalServiceUtil.createAddressExt(addressId);
			
			AddressExtLocalServiceUtil.addAddressExt(addressExt);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		address = AddressLocalServiceUtil.createAddress(addressId);
		address.setCreateDate(new java.util.Date());
		address.setNew(true);
		
		/*
		try {
			address = AddressLocalServiceUtil.updateAddress(address);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			address = AddressLocalServiceUtil.fetchAddress(addressId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		
		address.setClassNameId(ClassNameLocalServiceUtil.getClassNameId(Contact.class));
		address.setClassPK(user.getContactId());
		address.setUserId(user.getUserId());
		address.setCompanyId(user.getCompanyId());
		address.setModifiedDate(new java.util.Date());
		address.setUserName(user.getFullName());
		address.setPrimary(true);
		
		List<ListType> listTypes;
		try {
			listTypes = ListTypeServiceUtil.getListTypes(Contact.class.getName() + ".address");
			for (ListType listType: listTypes) {
				if (listType.getName().equalsIgnoreCase("personal")) {
					address.setTypeId(listType.getListTypeId());
					break;
				}
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		address.setCity(geoLocation.getCity());
		address.setCountryId(geoLocation.getCountryId());
		address.setRegionId(geoLocation.getRegionId());
		
		
		/*
		List<City> cities = new ArrayList<City>();
    	try {
			cities = CityLocalServiceUtil.getService().getRegion_Cities(Long.valueOf(regionId));
		} catch (SystemException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    	
    	
		if (cities.size() == 0){
			address.setCity(city);
		} else {
			address.setCity(newCity);
			City acity = null;
			long cityId;
			try {
				cityId = CounterLocalServiceUtil.increment();
				
				acity = CityLocalServiceUtil.createCity(cityId);
				acity.setCityId(cityId);
				acity.setStatus(true);
				acity.setCityName(newCity);
				acity.setRegionId(regionId);
				CityLocalServiceUtil.updateCity(acity);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		*/
							
		try {
			AddressLocalServiceUtil.updateAddress(address);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// setting AddressExt to capture the cityId
		try {
			addressExt = AddressExtLocalServiceUtil.fetchAddressExt(addressId);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (Validator.isNotNull(addressExt)) {
			addressExt.setCityId(geoLocation.getCityId());
			try {
				AddressExtLocalServiceUtil.updateAddressExt(addressExt);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static Log _log = LogFactoryUtil.getLog(
			DefaultLandingPageAction2.class);

}